package com.application.chiettinhdienluc.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.control.NhanCongInfoListControl;
import com.application.chiettinhdienluc.control.VattuInfoListControl;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.model.NhanCongChiTietModel;
import com.application.chiettinhdienluc.model.VatTuChiTietModel;
import com.application.chiettinhdienluc.utils.Utils;

public class NhanCongInfoAdapter extends BaseAdapter implements OnClickListener {
	public List<NhanCongChiTietModel> nhancongList;
	private List<NhanCongChiTietModel> nhancongListShowing;
	private CharSequence currentFilter;
	
	private Activity ac;
	public static final String Chiettinh = "chiettinh";

	private final static String TAG = NhanCongInfoAdapter.class.getSimpleName();
	private InputMethodManager inputMethodManager;
	private int myPosition;

	public NhanCongInfoAdapter(Activity context, ArrayList<NhanCongChiTietModel> nhancongList) {
		
		Collections.sort(nhancongList, new Comparator<NhanCongChiTietModel>(){
			  public int compare(NhanCongChiTietModel obj1, NhanCongChiTietModel obj2)
			  {
			    // TODO Auto-generated method stub
				  return (obj1.getOrder() < obj2.getOrder()) ? -1: (obj1.getOrder() > obj2.getOrder()) ? 1: (obj2.getTenCongviec().compareToIgnoreCase(obj1.getTenCongviec())) ;
			  }
			}); 
		
		this.nhancongList = new ArrayList<NhanCongChiTietModel>(nhancongList);
		this.nhancongListShowing = new ArrayList<NhanCongChiTietModel>(nhancongList);
		ac = context;
		inputMethodManager = (InputMethodManager) ac.getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	public void updateModel(ArrayList<NhanCongChiTietModel> nhancongList) {
		this.nhancongList = new ArrayList<NhanCongChiTietModel>(nhancongList);
		this.nhancongListShowing = new ArrayList<NhanCongChiTietModel>(nhancongList);
		notifyDataSetChanged();
		Log.d(TAG, "Reload data");

	}

	private class ViewHolder {
		TextView tvStt;
		TextView tvNameNhancong;
		TextView tvPrice;
		TextView tvKhoiluong;

		TextView tvDonvi;
		TextView tvTongtien;
		//ImageView imgCheck;
		
		RelativeLayout rlNhancong;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		// View view = null;
		if (convertView == null) {
			holder = new ViewHolder();
			LayoutInflater inflater = LayoutInflater.from(ac);
			convertView = inflater.inflate(R.layout.select_nhancong_item, null);
			holder.tvStt = (TextView) convertView.findViewById(R.id.tvStt);
			holder.tvNameNhancong = (TextView) convertView.findViewById(R.id.tvNameNhancong);
			holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
			holder.tvKhoiluong = (TextView) convertView.findViewById(R.id.tvKhoiluong);
			holder.tvDonvi = (TextView) convertView.findViewById(R.id.tvDonvi);
			holder.tvTongtien = (TextView) convertView.findViewById(R.id.tvTongtien);
			
			//holder.rlbtnItemMenu = (RelativeLayout) convertView.findViewById(R.id.rlbtnItemMenu);
			holder.rlNhancong = (RelativeLayout) convertView.findViewById(R.id.rlNhancong);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		try {
//			LayoutParams lp = holder.tvNameVattu.getLayoutParams();
//			lp.width = (int) (GlobalData.widthDevice / 1.5);
//			holder.tvNameVattu.setLayoutParams(lp);


			
//			holder.rlVattu.setVisibility(View.VISIBLE);
			NhanCongChiTietModel itemValue = (NhanCongChiTietModel)getItem(position);
			
			holder.tvStt.setText(position + 1 + ". ");
		
			holder.tvNameNhancong.setText(itemValue.getTenCongviec());
			holder.tvPrice.setText(Utils.formatDoubleNumber(Double.parseDouble(itemValue.getDongia()+"")) 
					+ " " + ac.getString(R.string.str_dong) + "/" 
					+ itemValue.getQuycach());
			holder.tvDonvi.setText(itemValue.getQuycach());
		
			if(itemValue.getKhoiLuong() > 0){
				holder.tvKhoiluong.setText(String.valueOf(Double.parseDouble(itemValue.getKhoiLuong() + "")));
			}else{
				holder.tvKhoiluong.setText("0");
			}
			
			double tongTien = Double.valueOf((itemValue.getDongia()) * itemValue.getKhoiLuong() + "");			
			if(tongTien > 0){
				holder.tvTongtien.setText(Utils.formatDoubleNumber(tongTien));
			}else{
				holder.tvTongtien.setText("0");
			}	
			
			if (itemValue.isCheck()) {
				convertView.setBackgroundResource(R.drawable.border);
				
			} else {
				convertView.setBackgroundResource(R.drawable.border_noneselect);
				
			}

			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					showDialog(position);
					
					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							edSoluongValue.requestFocus();
							inputMethodManager.showSoftInput(edSoluongValue, InputMethodManager.SHOW_IMPLICIT);
						}
					}, 300);
				}
			});
			
			Animation animation = null;
			animation = AnimationUtils.loadAnimation(ac, R.anim.push_up_in);
			convertView.startAnimation(animation);
			animation = null;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return nhancongListShowing.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return nhancongListShowing.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	/*
	 * dialog
	 */
	private Boolean isShowDialog = false;
	public Dialog dialog;
	public TextView tvName;
	public TextView tvMa;
	public TextView tvMaValue;
	public TextView tvTen;
	public TextView tvTenValue;
	public TextView tvSoluong;	

	public TextView tvDongiaValue;
	public EditText edSoluongValue;
	public TextView tvThanhTienValue;
	public Button btnSave;
	public Button btnCancel;
	
	private double donGiaValue;

	// public ImageView imgSet;

	public void showDialog(final int pos) {
		// custom dialog
		if (!isShowDialog) {
			
			NhanCongChiTietModel itemValue = (NhanCongChiTietModel)getItem(pos);
			
			myPosition = pos;
			isShowDialog = true;
			// imgSet = _imgSet;
			dialog = new Dialog(ac);
			dialog.getWindow();
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_layout);
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			
			this.tvName = (TextView)dialog.findViewById(R.id.tvName);
			tvName.setText(R.string.str_nhapkhoiluong_nhancong);			
			this.tvMa = (TextView)dialog.findViewById(R.id.tvMa);
			tvMa.setText(R.string.str_maCongViec);			
			this.tvTen = (TextView)dialog.findViewById(R.id.tvTen);
			tvTen.setText(R.string.str_tenCongviec);			
			this.tvSoluong = (TextView)dialog.findViewById(R.id.tvSoluong);
			tvSoluong.setText(R.string.str_khoiLuong);

			this.tvMaValue = (TextView) dialog.findViewById(R.id.tvMaValue);
			this.tvTenValue = (TextView) dialog.findViewById(R.id.tvTenValue);
			this.tvDongiaValue = (TextView) dialog.findViewById(R.id.tvDongiaValue);
			this.edSoluongValue = (EditText) dialog.findViewById(R.id.edSoluongValue);
			this.tvThanhTienValue = (TextView) dialog.findViewById(R.id.tvThanhTienValue);
			this.btnSave = (Button) dialog.findViewById(R.id.btnSave);
			this.btnCancel = (Button) dialog.findViewById(R.id.btnCancel);

			
			tvMaValue.setText(itemValue.getMaCongViec());
			tvTenValue.setText(itemValue.getTenCongviec());
			
			donGiaValue = Double.parseDouble(itemValue.getDongia()+ "");
			
			tvDongiaValue.setText(Utils.formatDoubleNumber(donGiaValue)
					+ " " + ac.getString(R.string.str_dong) 
					+ "/" + itemValue.getQuycach() );
			
			btnCancel.setOnClickListener(this);
			btnSave.setOnClickListener(this);
			edSoluongValue.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					String text = edSoluongValue.getText().toString();
					if (!TextUtils.isEmpty(text)) {
						tvThanhTienValue.setText(Utils.formatDoubleNumber((Double.parseDouble(text) * donGiaValue)));
					} else {
						tvThanhTienValue.setText("0");
					}

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});

			dialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					isShowDialog = false;
				}
			});

			dialog.show();
		}

	}

	public Boolean checkConstraint() {

		if (TextUtils.isEmpty(edSoluongValue.getText().toString())) {
			Toast.makeText(ac, ac.getString(R.string.str_toast), Toast.LENGTH_SHORT).show();
			return false;
		}

		return true;
	}

	@Override
	public void onClick(View v) {
		if (v == btnCancel) {
			dialog.dismiss();
		}
		
		if (v == btnSave) {
			if (checkConstraint()) {
//				NhanCongChiTietModel ncct = (NhanCongChiTietModel)getItem(myPosition);
				
				double khoiluong = Double.valueOf(edSoluongValue.getText().toString());
				
				nhancongListShowing.get(myPosition).setKhoiLuong(khoiluong);
				nhancongListShowing.get(myPosition).setCheck(khoiluong > 0);
				
				if(GlobalData.SelectedNhanCongList != null) 
					GlobalData.SelectedNhanCongList.clear();
				else
					GlobalData.SelectedNhanCongList = new NhanCongInfoListControl();
				
				for (int k = 0; k < nhancongList.size(); k++) {
					if(nhancongList.get(k).getMaCongViec().equals(nhancongListShowing.get(myPosition).getMaCongViec()))
					{
						nhancongList.get(k).setKhoiLuong(nhancongListShowing.get(myPosition).getKhoiLuong());
						nhancongList.get(k).setCheck(nhancongListShowing.get(myPosition).isCheck());
					}
					
					if (nhancongList.get(k).isCheck()) 
					{
						nhancongList.get(k).setOrder(0);
						
						if(!GlobalData.SelectedNhanCongList.contain(nhancongList.get(k).getMaCongViec()))
							GlobalData.SelectedNhanCongList.add(nhancongList.get(k));
					}
					else
					{
						if(GlobalData.SelectedVatTuList.contain(nhancongList.get(k).getMaCongViec()))
						{
							for(int j = GlobalData.SelectedVatTuList.size() - 1; j >= 0; j--)
							{
								if(GlobalData.SelectedVatTuList.get(j).getMaVatTu().equals(nhancongList.get(k).getMaCongViec()))
									GlobalData.SelectedVatTuList.remove(j);
							}
							
							nhancongList.get(k).setOrder(1);
						}
						else
						{
							if(GlobalData.nhancongInfoListInDB.contains(nhancongList.get(k).getMaCongViec()))
							{
								GlobalData.SelectedNhanCongList.add(nhancongList.get(k));
								
								if(nhancongList.get(k).isCheck())
									nhancongList.get(k).setOrder(0);
								else
									nhancongList.get(k).setOrder(1);
							}
						}
					}
				}
				
//				for(int i = 0; i < nhancongListShowing.size(); i++) {
//					if(nhancongListShowing.get(i).isCheck()) {
//						//order++;
//						nhancongListShowing.get(i).setOrder(0);
//						
//						if(!GlobalData.SelectedNhanCongList.contain(nhancongListShowing.get(i).getMaCongViec()))
//							GlobalData.SelectedNhanCongList.add(nhancongListShowing.get(i));
//					}
//					else
//					{
//						if(!GlobalData.SelectedNhanCongList.contain(nhancongListShowing.get(i).getMaCongViec()))
//						{
//							if(GlobalData.nhancongInfoListInDB.contains(nhancongListShowing.get(i).getMaCongViec()))
//							{
//								GlobalData.SelectedNhanCongList.add(nhancongListShowing.get(i));
//								nhancongListShowing.get(i).setOrder(0);
//							}
//						}	
//						else
//							nhancongListShowing.get(i).setOrder(1);						
//					}
//				}
				
				Collections.sort(nhancongListShowing, new Comparator<NhanCongChiTietModel>(){
					  public int compare(NhanCongChiTietModel obj1, NhanCongChiTietModel obj2)
					  {
					    // TODO Auto-generated method stub
						  return (obj1.getOrder() < obj2.getOrder()) ? -1: (obj1.getOrder() > obj2.getOrder()) ? 1: (obj1.getTenCongviec().compareToIgnoreCase(obj2.getTenCongviec())) ;
					  }
					}); 
				
				NhanCongInfoAdapter.super.notifyDataSetChanged();
  
				sendMessage(MainApplication.getAppContext(), "com.application.chiettinhdienluc.ui.Selected_NhanCong_Change");
				dialog.dismiss();
			}
		}
	}

	public void sendMessage(Context cont, String Action) {
		Intent intent = new Intent(Action);
		
		cont.sendBroadcast(intent);
	}

	public void setItemList(List<NhanCongChiTietModel> nhancongList) {	
		this.nhancongList = new ArrayList<NhanCongChiTietModel>(nhancongList);
		this.nhancongListShowing = new ArrayList<NhanCongChiTietModel>(nhancongList);
	}
	
	@Override
	public void notifyDataSetChanged() {
		if (currentFilter!=null) getFilter().filter(currentFilter);
		else nhancongListShowing = new ArrayList<NhanCongChiTietModel>(nhancongList);
		super.notifyDataSetChanged();
	}
	
	/**
     * Lock used to modify the content of {@link #friendList}. Any write operation
     * performed on the array should be synchronized on this lock. This lock is also
     * used by the filter (see {@link #getFilter()} to make a synchronized copy of
     * the original array of data.
     */
    private final Object mLock = new Object();
    
    private ArrayFilter mFilter;

    /**
     * Sorts the content of this adapter using the specified comparator.
     *
     * @param comparator The comparator used to sort the objects contained
     *        in this adapter.
     */
//    public void sort(Comparator<? super VattuModel> comparator) {
//        synchronized (mLock) {
//            if (vattuListShowing != null) {
//                Collections.sort(vattuListShowing, comparator);
//            } else {
//                Collections.sort(itemList, comparator);
//            }
//        }
//        notifyDataSetChanged();
//    }

    /**
     * {@inheritDoc}
     */
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ArrayFilter();
        }
        return mFilter;
    }

	/**
     * <p>An array filter constrains the content of the array adapter with
     * a prefix. Each item that does not start with the supplied prefix
     * is removed from the list.</p>
     */
	private class ArrayFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            if (nhancongListShowing == null) {
                synchronized (mLock) {
                	nhancongListShowing = new ArrayList<NhanCongChiTietModel>(nhancongList);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<NhanCongChiTietModel> list;
                synchronized (mLock) {
                    list = new ArrayList<NhanCongChiTietModel>(nhancongList);
                }
                
                Collections.sort(list, new Comparator<NhanCongChiTietModel>(){
                    public int compare(NhanCongChiTietModel obj1, NhanCongChiTietModel obj2)
                    {
                      // TODO Auto-generated method stub
                     return (obj1.getOrder() < obj2.getOrder()) ? -1: (obj1.getOrder() > obj2.getOrder()) ? 1: (obj1.getTenCongviec().compareToIgnoreCase(obj2.getTenCongviec())) ;
                    }
                  });
                
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase(Locale.getDefault());
                String filterText = Utils.convertSignToNoSign(prefixString);
                ArrayList<NhanCongChiTietModel> values;
                synchronized (mLock) {
                    values = new ArrayList<NhanCongChiTietModel>(nhancongList);
                }

                final int count = values.size();
                final ArrayList<NhanCongChiTietModel> newValues = new ArrayList<NhanCongChiTietModel>();
                
                for (int i = 0; i < count; i++) {
                    final NhanCongChiTietModel value = values.get(i);
                    String nameNoSign = Utils.convertSignToNoSign(value.getTenCongviec()); 
                    if(nameNoSign.contains(filterText)) 
					{
                    	newValues.add(value);							
					}
                }
                
                Collections.sort(newValues, new Comparator<NhanCongChiTietModel>(){
                    public int compare(NhanCongChiTietModel obj1, NhanCongChiTietModel obj2)
                    {
                      // TODO Auto-generated method stub
                     return (obj1.getOrder() < obj2.getOrder()) ? -1: (obj1.getOrder() > obj2.getOrder()) ? 1: (obj1.getTenCongviec().compareToIgnoreCase(obj2.getTenCongviec())) ;
                    }
                  });

                results.values = newValues;
                results.count = newValues.size();
            }

            return results;
        }

        @SuppressWarnings("unchecked")
		@Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
        	currentFilter = constraint;
        	nhancongListShowing = (List<NhanCongChiTietModel>) results.values;
            if (results.count > 0) {
                NhanCongInfoAdapter.super.notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

}
